import { STUDYDATA, CHANGEHANDOUTBTNTYPE, CHANGSTUDYINGID, NODEINDEX, SOURCEINFO, CHANGESOURCEINFO, CHANGETOPICINFO, CHANGESUBMITDATA } from '../types/study'
import { createAction } from 'redux-actions'
import study from '@/api/study'
import topic from '@/api/topic'
import wepy from 'wepy'
import tips from '@/util/tips'

// 学习包数据
export const getStudyData = createAction(STUDYDATA, (params) => {
	return new Promise(resolve=>{
	  study.getData(params).then(res => resolve(res))
	})
})

// 讲义按钮状态
export const changeHandoutBtn = createAction(CHANGEHANDOUTBTNTYPE, (params) => {
	return new Promise(resolve => resolve(params))
})

// 修改正在学习的学习包id
export const changeStudyingId = createAction(CHANGSTUDYINGID, (params) => {
	return new Promise(resolve => resolve(params))
})

// 修改讲义及做题顶部章节
export const changeNodeIndex = createAction(NODEINDEX, (params) => {
	return new Promise(resolve => resolve(params))
})

// 获取习题信息
export const getSourceInfo = createAction(SOURCEINFO, (params) => {
	return new Promise(resolve => {
    // 本知识点有做题记录并且未做完不调用接口
    if(JSON.stringify(wepy.$store.getState().study.sourceInfo) !== '{}' && params.knowledgeNodeId === wepy.$store.getState().study.sourceInfo.obj.id && wepy.$store.getState().study.topicInfo.isPass !== 4 && wepy.$store.getState().study.topicInfo.isPass !== 2) {
      resolve(wepy.$store.getState().study.sourceInfo)
    } else {
			tips.loading()
      topic.topicData(params).then(res => {
				tips.loaded()
        let list = res.obj.exerList
        list.forEach((i, index) => {
          i.optionList.forEach(j => {
            j.active = 0
            j.parentindex = index
          })
        })
        let data = {
          index: 0,
          trueNum: 0,
          falseNum: 0,
          isPass: 0,
          btnStatus: false,
          showAnalysis: false,
          eachFlag: 1
        }
        wepy.$store.dispatch(changeTopicInfo(data))
        wepy.$store.dispatch(changeSubmitData({}))
        resolve(res)
      })
    }
  })
})

// 修改学习包
export const changeSourceInfo = createAction(CHANGESOURCEINFO, (params) => {
	return new Promise(resolve => resolve(params))
})

// 修改做题信息
export const changeTopicInfo = createAction(CHANGETOPICINFO, (params) => {
	return new Promise(resolve => resolve(params))
})

// 修改将要提交到服务端的做题信息
export const changeSubmitData = createAction(CHANGESUBMITDATA, (params) => {
	return new Promise(resolve => resolve(params))
})
